<template>
  <div class="img-verify">
    <canvas
      ref="verify"
      :style="{ width: '120px', height: '42px' }"
      @click="handleDraw"
    ></canvas>
  </div>
</template>
n
<script lang="ts" setup>
import { reactive, onMounted, ref } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
const userStore = useUserStoreHook();
const verify = ref();
let  captcha='';
const state = reactive({
  pool: "1234567890", // 验证码包含那些
  // pool: "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890",
  width: 300, // canvas宽
  height: 160, // canvas高
});
onMounted(() => {
  // 初始化绘制图片验证码
  draw();
});

// 点击图片重新绘制
const handleDraw = () => {
  draw();
};

// 随机数
const randomNum = (min: number, max: number) => {
  return parseInt(String(Math.random() * (max - min) + min));
};
// 随机颜色
const randomColor = (min: number, max: number) => {
  const r = randomNum(min, max);
  const g = randomNum(min, max);
  const b = randomNum(min, max);
  return `rgb(${r},${g},${b})`;
};
// 绘制干扰点
const drawDot = (ctx: {
  fillStyle: string;
  beginPath: () => void;
  arc: (
    arg0: number,
    arg1: number,
    arg2: number,
    arg3: number,
    arg4: number
  ) => void;
  fill: () => void;
}) => {
  for (let i = 0; i < 100; i++) {
    ctx.fillStyle = randomColor(0, 255);
    ctx.beginPath();
    ctx.arc(randomNum(0, 300), randomNum(0, 160), 1, 0, 2 * Math.PI);
    ctx.fill();
  }
};

// 绘制图片
const draw = () => {
  captcha=''
  const ctx = verify.value.getContext("2d");
  // 填充颜色
  ctx.fillStyle = randomColor(180, 230);
  // 填充的位置
  ctx.fillRect(0, 0, state.width, state.height);
  // 随机产生字符串，并且随机旋转
  for (let i = 0; i < 4; i++) {
    // 随机的一个字符
    const text = state.pool[randomNum(0, state.pool.length)];
    // 随机的字体大小
    const fontSize = randomNum(65, 90);
    // 字体随机的旋转角度
    const deg = randomNum(-30, 30);
    ctx.font = fontSize + "px Simhei";
    ctx.textBaseline = "top";
    ctx.fillStyle = randomColor(80, 150);
    ctx.save();
    ctx.translate(65 * i + 15, 50);
    ctx.rotate((deg * Math.PI) / 180);
    ctx.fillText(text, 15 + 5, 0);
    ctx.restore();
    captcha = captcha + text
  }
  // 绘制干扰点
  drawDot(ctx);
  handleChange(captcha);
};
const handleChange = (value: string) => {
  userStore.changeState(value);
};
</script>
